
import React, { useEffect, useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { addArticle, getArticle, deleteArticle } from '../../common/constant';

const { Item } = Form;

function Article() {

  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);

  const fetchData = () => {
    getArticle()
      .then(res => setDataSource(res.result))
  }

  useEffect(fetchData, [])

  // 清空
  const onReset = () => form.resetFields();

  // 提交
  const onFinish = value => {
    addArticle(value)
      .then(res => {
        if (res) {
          message.success('新增成功');
          fetchData();
          onReset()
        }
      })
      .catch(err => message.error(err))
  }

  return (
    <>
      <Form
        name="article"
        form={form}
        onFinish={onFinish}
        onFinishFailed={err => { console.error(err) }}
      >
        <Item
          label="标题"
          name="title"
          rules={[
            { required: true, message: '请输入标题' },
            { max: 20, message: '最大为20个字符' }
          ]}
        >
          <Input placeholder='请输入标题' />
        </Item>
        <Item
          label="内容"
          name="content"
          rules={[{ required: true, message: '请输入内容' }]}
        >
          <Input.TextArea
            placeholder='请输入内容'
            rows={4}
          />
        </Item>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form>
      {dataSource?.map((item, i) => (
        <div
          key={item.id}
          style={{ border: '1px dashed skyblue' }}
        >
          <div>第{i + 1}部分</div>
          <div>标题: {item.title}</div>
          <div>内容: {item.content}</div>
          <div
            style={{ cursor: 'pointer' }}
            onClick={() => {
              deleteArticle(item.id)
                .then(res => res && fetchData())
            }
            }>删除该部分</div>
        </div>
      ))}
    </>
  )
}

export default Article